package com.luzh.myspring.context.support;

import com.luzh.myspring.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import com.luzh.myspring.beans.BeanException;
import com.luzh.myspring.beans.factory.ConfigurableListableBeanFactory;
import com.luzh.myspring.beans.factory.PropertyPlaceholderConfigurer;
import com.luzh.myspring.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.luzh.myspring.beans.factory.config.BeanFactoryPostProcessor;
import com.luzh.myspring.beans.factory.config.BeanPostProcessor;
import com.luzh.myspring.context.ApplicationEvent;
import com.luzh.myspring.context.ApplicationListener;
import com.luzh.myspring.context.ConfigurableApplicationContext;
import com.luzh.myspring.context.event.ApplicationEventMulticaster;
import com.luzh.myspring.context.event.ContextClosedEvent;
import com.luzh.myspring.context.event.ContextRefreshedEvent;
import com.luzh.myspring.context.event.SimpleApplicationEventMulticaster;
import com.luzh.myspring.core.convert.ConversionService;
import com.luzh.myspring.core.io.DefaultResourceLoader;

import java.util.Collection;
import java.util.Map;

/**
 * 可刷新的应用上下文（刷新容器，获取bean，发布事件）
 */
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {

    public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
    //事件广播器
    private ApplicationEventMulticaster applicationEventMulticaster;

    /**
     * 对beanFactory的创建及配置
     * @throws BeanException
     */
    @Override
    public void refresh() throws BeanException {
        //创建容器，加载原始xml文件，扫描注解bean
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        //实例化并执行beanFactory处理器（占位符解析）
        invokeBeanFactoryPostProcessors(beanFactory);
        //实例化并注册bean处理器
        registerBeanPostProcessors(beanFactory);
        //注册事件广播器
        initApplicationEventMulticaster();
        //实例化并添加监听器
        registerListeners();
        //注册类型转换服务
        finishBeanFactoryInitialization(beanFactory);
        //预实例化其他bean对象
        beanFactory.preInstantiateSingletons();
        //刷新完成
        finishRefresh();
    }
    protected abstract void refreshBeanFactory() throws BeanException;

    protected abstract ConfigurableListableBeanFactory getBeanFactory();

    /**
     * 添加自定义类型转换服务
     * @param beanFactory
     */
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        if (beanFactory.containsBean("conversionService")) {
            Object conversionService = beanFactory.getBean("conversionService");
            if (conversionService instanceof ConversionService) {
                beanFactory.setConversionService((ConversionService) conversionService);
            }
        }
    }

    /**
     * 注册广播器
     */
    private void initApplicationEventMulticaster() {
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, applicationEventMulticaster);
    }

    /**
     * 获取监听器并添加到广播器中
     */
    private void registerListeners() {
        Collection<ApplicationListener> applicationListeners = getBeansOfType(ApplicationListener.class).values();
        for (ApplicationListener<?> listener : applicationListeners) {
            applicationEventMulticaster.addApplicationListener(listener);
        }
    }

    private void finishRefresh() {
        publishEvent(new ContextRefreshedEvent(this));
    }

    /**
     * 发布事件
     * @param event
     */
    @Override
    public void publishEvent(ApplicationEvent event) {
        applicationEventMulticaster.multicastEvent(event);
    }

    /**
     * 获取beanFactory处理器并执行
     * @param beanFactory
     */
    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        new PropertyPlaceholderConfigurer().postProcessBeanFactory(beanFactory);
        Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessorMap =beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);
        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessorMap.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }

    }

    /**
     * 获取bean处理器并注册
     * @param beanFactory
     */
    private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        //添加内置处理器
        beanFactory.addBeanPostProcessor(new DefaultAdvisorAutoProxyCreator(beanFactory));
        beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(beanFactory));
        beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
        Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeansOfType(BeanPostProcessor.class);
        for (BeanPostProcessor beanPostProcessor : beanPostProcessorMap.values()) {
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }

    @Override
    public void registerShutdownHook() {
        //添加钩子函数
        Runtime.getRuntime().addShutdownHook(new Thread(this::close));
    }

    @Override
    public void close() {
        publishEvent(new ContextClosedEvent(this));
        getBeanFactory().destroySingletons();
    }

    @Override
    public boolean containsBean(String name) {
        return getBeanFactory().containsBean(name);
    }

    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeanException {
        return getBeanFactory().getBeansOfType(type);
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return getBeanFactory().getBeanDefinitionNames();
    }

    @Override
    public Object getBean(String name) throws BeanException {
        return getBeanFactory().getBean(name);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeanException {
        return getBeanFactory().getBean(name, args);
    }

    @Override
    public <T> T getBean(String name, Class<T> requiredType) throws BeanException {
        return getBeanFactory().getBean(name, requiredType);
    }
    @Override
    public <T> T getBean(Class<T> requiredType) throws BeanException {
        return getBeanFactory().getBean(requiredType);
    }
}
